package com.changeover.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractView;

import com.changeover.domain.User;
import com.changeover.service.IControlUserService;

@Controller
@RequestMapping(value = "/users")
public class ControlUserController {
	
	@Autowired
	private IControlUserService controlUserService;

	@RequestMapping(method = RequestMethod.GET)
	public String list(Map<String, Object> map) {
		List<User> users = controlUserService.getAllUsers();
		map.put("users", users);
		return "users";
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@RequestParam Integer id, @RequestParam String name,  @RequestParam String passwd) {
		controlUserService.saveUser(id, name, passwd);
		return "redirect:/users";
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable Integer id) {
		controlUserService.deleteUser(id);
		return "redirect:/users";
	}
	
	@RequestMapping(value = "/viewTest", method = RequestMethod.GET)
	public View viewTest() {
		return new View() {
			
			public void render(Map<String, ?> model, HttpServletRequest request,
					HttpServletResponse response) throws Exception {
				response.getWriter().print("Hello world! From view.");
			}
			
			public String getContentType() {
				return AbstractView.DEFAULT_CONTENT_TYPE;
			}
		};
	}
	
}
